<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">
        <el-card class="mx-11 my-0">
          <template #header>
            <div class="flex items-center">
              <Calendar style="width: 1em; height: 1em; vertical-align: middle" />
              <span style="vertical-align: middle" class="ml-2">二维码展示</span>
            </div>
          </template>
          <div v-loading="loading" element-loading-text="加载中" style="width: 100%; height: 300px" class="flex justify-center">
            <div ref="qrcodeRef" style="width: 300px; height: 300px"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import QRCode from "qrcode-generator";
const qrcodeRef = ref<HTMLDivElement | null>(null);
const loading = ref(false);
const intervalId = ref<ReturnType<typeof setTimeout>>();

// 生成二维码
async function updateQRCode() {
  loading.value = true;
  const qrcode = QRCode(0, "L");
  //将时间戳信息添加到URL信息中去
  const randomString = Math.random().toString(36).substring(2, 15);
  qrcode.addData(`${randomString}`);
  qrcode.make();
  const qrcodeImage = await qrcode.createImgTag(25, 25);
  if (qrcodeRef.value) {
    qrcodeRef.value.innerHTML = qrcodeImage;
  }
  loading.value = false;
}

onMounted(() => {
  updateQRCode();
  intervalId.value = setInterval(updateQRCode, 3000);
});

onBeforeMount(() => {
  clearInterval(intervalId.value);
});
</script>

<style scoped></style>
